#include "TextureManager.h"
#include "Director.h"

TextureManager::TextureManager(void)
{
}


TextureManager::~TextureManager(void)
{
	if( !_textureMap.empty() )
	{
		for( StrTexture_Map::const_iterator i = _textureMap.begin(); i != _textureMap.end(); ++i)
		{
			if( i->second )
				delete i->second;
		}
		_textureMap.clear();
	}//end empty
}

Texture* TextureManager::getTexture(string name)
{
	if( _textureMap.find(name) == _textureMap.end() )
		if( loadTexture(name) )
			return _textureMap[name];
		else
			return NULL;

	return _textureMap[name];
}


bool TextureManager::loadTexture(string name)
{
	LPDIRECT3DTEXTURE9 tempTexture = NULL;
	LPDIRECT3DDEVICE9 device = SharedDirector()->GetD3D9()->GetDevice();

	D3DXIMAGE_INFO	tempInfo;
	D3DXGetImageInfoFromFile(name.c_str(), &tempInfo);
	D3DXCreateTextureFromFileEx(
		device,
		name.c_str(),
		tempInfo.Width,
		tempInfo.Height,
		D3DX_DEFAULT,
		0,
		D3DFMT_UNKNOWN,//D3DFMT_FROM_FILE,
		D3DPOOL_MANAGED,
		D3DX_DEFAULT, 
		D3DX_DEFAULT, 
		NULL, 
		NULL, 
		NULL,
		&tempTexture);//end FormFileEx

	if( tempTexture )
	{
		Texture* addTexture = new Texture();
		addTexture->texture = tempTexture;
		addTexture->width = tempInfo.Width;
		addTexture->height = tempInfo.Height;

		_textureMap.insert( StrTexture_Map::value_type(name, addTexture));
		return true;
	}
	return false;
}
